package com.hellobike.haxing.filter;

import com.alibaba.fastjson.JSON;
import com.hellobike.haxing.anno.NoAuth;
import com.hellobike.haxing.common.RedisKeyConstant;
import com.hellobike.haxing.order.result.Result;
import com.hellobike.haxing.user.vo.UserVo;
import com.hellobike.haxing.util.RedisUtil;
import com.hellobike.haxing.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    private UserUtil userUtil;
    private RedisUtil redisUtil;

    public LoginInterceptor(RedisUtil redisUtil, UserUtil userUtil) {
        this.redisUtil = redisUtil;
        this.userUtil = userUtil;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /**
         * 显示申明不需要权限验证
         */
        String token = request.getHeader("Access-Token");
        log.info("token-infof:{}", token);
        UserUtil.tokenThread.set(token);
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        if (redisUtil.ttl(RedisKeyConstant.FAKE_PAGE_TAG) > -2 && request.getRequestURI().endsWith("home")) {
            return true;
        }
        if (handler instanceof HandlerMethod) {
            NoAuth noAuth = ((HandlerMethod) handler).getMethod().getDeclaringClass().getAnnotation(NoAuth.class);
            if (noAuth != null) {
                return true;
            }
            NoAuth noAuth1 = ((HandlerMethod) handler).getMethod().getAnnotation(NoAuth.class);
            if (noAuth1 != null) {
                return true;
            }
        }

        boolean authPass = true;
        if (StringUtils.isBlank(token)) {
            authPass = false;
        }
        UserVo userVo = userUtil.getUser(token);
        if (userVo == null) {
            authPass = false;
        }
        if (!authPass) {
            Result result = Result.noauth("请先登录");
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(JSON.toJSONString(result));
            response.getWriter().flush();
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        UserUtil.tokenThread.remove();
    }
}
